<template>
  <div class="app-container">
    <div class="customContainer" v-show="tab_view==1">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                          :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
                  placeholder="选择筛选条件"
                  v-model="formInline.type"
                  style="width:150px"
                  filterable
          >
            <el-option
                    v-for="item in SearchList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-show="formInline.type=='0'" style="width: 200px" v-model="formInline.sample_name" placeholder="请输入短信名称" @keyup.enter.native="fetchData"></el-input>
          <el-input v-show="formInline.type=='1'" style="width: 200px" v-model="formInline.template_name" placeholder="请输入模板名称" @keyup.enter.native="fetchData"></el-input>
          <el-input v-show="formInline.type=='2'" style="width: 200px" v-model="formInline.template_code" placeholder="请输入模板CODE" @keyup.enter.native="fetchData"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">新建短信</el-button>
        <el-button class="pull-right" style="margin-right: 20px" type="primary" size="small" @click="goToPage(1)">发送记录</el-button>
      </el-form>

      <!--       表格内容-->
      <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading"
                :default-sort = "{prop: 'create_time', order: 'descending'}">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="短信名称" prop="name"></el-table-column>
        <el-table-column align="center" label="短信内容" width="300px">
          <template slot-scope="scope">
            <div class="longlinks">{{scope.row.content}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="模板名称" prop="template_name"></el-table-column>
        <el-table-column align="center" label="模板CODE" prop="code"></el-table-column>
        <el-table-column align="center" label="创建时间" prop="create_time" sortable></el-table-column>
        <el-table-column align="center" label='操作'>
          <template slot-scope="scope">
            <el-button  type="primary" plain size="mini" @click="goToPage(2,scope.row)">发短信</el-button>
            <el-button  type="primary" plain size="mini" @click="detailsList(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 短信详情-->
    <div v-show="tab_view==2" class="customContainer">
      <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
      <div class="tab_title">{{top_title}}</div>
      <div class="info">
        <el-form
            :model="infoFormObject"
            ref="infoForm"
            :rules="rules"
            :disabled="isDisabled"
            label-width="80px"
        >
          <el-form-item label="模板类型" label-width="100px">
            <template>
              <div style="font-weight: bold">{{infoFormList.type==1?'推广短信':'通知短信'}}</div>
              <div class="colortext" v-show="infoFormList.type==1">
                <p>1.向手机号码发送的包含推广信息的短信，短信内容为经过审核的模板内容，不支持通过变量替换实现个性短信定制。</p>
                <p>2.通常用于向注册用户和潜在客户发送通知和推广信息，包括促销活动通知、业务推广、新产品宣讲、会员关怀等商品与活动的推广信息，可以增加企业产品曝光率、提高产品和企业的知名度。</p>
              </div>
              <div class="colortext"  v-show="infoFormList.type==2">
                <p>1.向手机号码发送的通知类短信，支持通过变量替换实现个性短信定制。</p>
                <p>2.通常用于向注册用户下发系统相关信息，包括升级或维护、服务开通、价格调整、 订单确认、物流动态、消费确认、 支付通知等普通通知短信。</p>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="模板CODE" label-width="100px">
            <el-input
                v-model="infoFormList.code"
                style="width:80%"
                disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="模板名称" label-width="100px">
            <el-input
                v-model="infoFormList.name"
                style="width:80%"
                disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="模板内容" label-width="100px">
            <el-input
                type="textarea"
                :rows="3"
                v-model="infoFormList.content"
                style="width:80%"
                disabled
            ></el-input>
          </el-form-item>

          <div v-show="infoFormObject.content_json.length">
            <div class="op_title" >模板变量</div>
            <div v-for="(val,index) in infoFormObject.content_json" :key="index" >
              <el-form-item  v-for="(item,key,i) in val" :key="key"  :label="'变量'+(index+1)" label-width="100px" :prop="key">
                <el-input
                    type="text"
                    :rows="3"
                    :maxlength="20"
                    v-model="infoFormObject.content_json[index][key]"
                    :placeholder="'${'+key+'}'"
                    style="width:80%"
                    show-word-limit
                ></el-input>
              </el-form-item>
            </div>
          </div>

          <div class="op_title">短信预览</div>
          <el-form-item label="" label-width="100px" prop="NewContent">
            <template>
              <el-input
                  type="textarea"
                  :rows="3"
                  v-model="infoFormObject.NewContent"
                  style="width:80%"
                  disabled
              ></el-input>
              <div class="num" style="width:80%">
                <div class="font"><span :class="infoFormObject.NewContent.length>70?'red':''">{{infoFormObject.NewContent.length}}</span>/70</div>
              </div>
              <div style="width:80%;color:red" v-show="infoFormObject.NewContent.length>70">
                {{isDisabled?'短信内容超过字数上限，请重新调整。':'短信内容超过字数上限，将拆成多条发送。'}}
              </div>
            </template>
          </el-form-item>

          <div class="op_title">短信名称</div>
          <el-form-item  label="" label-width="100px" prop="MessageName">
            <el-input
                :maxlength="15"
                placeholder="请输入短信名称"
                v-model="infoFormObject.MessageName"
                style="width:80%"
            ></el-input>
          </el-form-item>

<!--          <div class="op_title">发送对象</div>-->
<!--          <el-form-item  label="门店：" label-width="100px" prop="store_id">-->
<!--            <el-select-->
<!--                placeholder="选择门店"-->
<!--                v-model="infoFormObject.store_id"-->
<!--                style="width:300px"-->
<!--                filterable-->
<!--            >-->
<!--              <el-option-->
<!--                  v-for="item in store_list"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="手机号" label-width="100px" prop="phoneNumber">-->
<!--            <el-input-->
<!--                :maxlength="15"-->
<!--                placeholder="纯数字最多输入11位"-->
<!--                v-model="infoFormObject.phoneNumber"-->
<!--                style="width:80%"-->
<!--            ></el-input>-->
<!--          </el-form-item>-->
        </el-form>
      </div>
      <div style="text-align:right;margin-bottom:20px" v-show="!isDisabled">
        <el-button
            @click="editClick()"
            type="primary"
            size="small"
        >保存</el-button>
      </div>
    </div>

    <!-- 弹框 -->
    <el-dialog  title="选择模板" :visible.sync="addTypeDialog" width="1200px" height="500px">
      <div class="main">
        <el-form :inline="true" :model="formDialongInline" class="demo-form-inline" size="small">
          <el-form-item>
            <el-select
                placeholder="选择模板"
                v-model="formDialong.tem_type"
                style="width:150px"
                filterable
            >
              <el-option
                  v-for="item in template_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-show="formDialong.tem_type==0" style="width: 200px" v-model="formDialong.name" placeholder="请输入模板名称" @keyup.enter.native="dialongFetchData">
            </el-input>
            <el-input v-show="formDialong.tem_type==1" style="width: 200px" v-model="formDialong.code" placeholder="请输入模板CODE" @keyup.enter.native="dialongFetchData">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="dialongFetchData">搜索</el-button>
          </el-form-item>
        </el-form>
        <!--       表格内容-->
        <el-table highlight-current-row :data="formDialongList" border size="mini" v-loading.body="formDialongInline.listLoading" max-height="500px"
                  :default-sort = "{prop: 'create_time', order: 'descending'}">
          <el-table-column align="center" label="模板名称" prop="name"></el-table-column>
          <el-table-column align="center" label="模板内容" width="300px">
            <template slot-scope="scope">
              <div class="longlinks">{{scope.row.content}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="模板类型">
            <template slot-scope="scope">
              <div>{{scope.row.type==1?'推广短信':'通知短信'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="模板CODE" prop="code" width="100px"></el-table-column>
          <el-table-column align="center" label="创建时间" prop="create_time" sortable></el-table-column>
          <el-table-column align="center" label='操作'>
            <template slot-scope="scope">
              <el-button  type="primary" plain size="mini" @click="contentDetails(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="bottom_box">
          <el-pagination class="pull-left" background @current-change="dialongCurrentChange" :current-page.sync="formDialongInline.currentPage" :page-size="20"
                         layout="prev, pager, next, jumper" :total="formDialongInline.totalDataNumber">
          </el-pagination>
        </div>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box" v-show="tab_view==1">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                     layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getLinkInfoPage,
  getLinkInfo,
  getMessageInfo,
  getMessageInfoPage,
  sampleCreate
} from "@/api/information/shortNote";
import {
  pickerOptionsY,
  pickerDateOneMonth,
  optionMaxTime369
} from "@/utils";
import {
  mobile,
  notCharmap
} from "@/utils/validate";
export default {
  data(){
    const vPname = (rule, value, callback) => {
      if(!mobile(value)){
        callback(new Error("请输入正确的手机号"));
      }else{
        callback();
      }
    };
    const vName = (rule, value, callback) => {
      if (value.length<1) {
        callback(new Error("请输入短信名字（1-15个字符）"));
      } else {
        if (!notCharmap(value)) {
          callback(new Error("名称不能包含特殊字符"));
        } else {
          callback();
        }
      }
    };
    const vStore = (rule, value, callback) => {
      if (this.infoFormObject.store_id =="") {
        callback(new Error("请选择要发送的门店"));
      } else {
        callback();
      }
    };

    return{
      list: [],  //数据
      listLoading: false,  //表格换场动画
      pickerOptions: pickerOptionsY(),
      pickerDate: pickerDateOneMonth(),
      store_list: [],
      formInline: {   //主页的搜索数据
        begin_time: "",//开始时间，结束时间
        end_time: "",
        type:"0",
        sample_name:"",
        template_name:"",
        template_code:""
      },
      SearchList:[{id:"0",name:"短信名称"},{id:"1",name:"模板名称"},{id:"2",name:"模板CODE"}],
      addTypeDialog:false,
      currentPage: 1,  //主页的分页
      totalDataNumber: 0, //主页的总条目数
      tab_view:1,  //显示短信详情页
      isDisabled:false,
      top_title: "短信模板", //详情页的标题
      infoFormList:[], //短信详情模板数据
      infoForm:{ //详情页里的数据
        temName:"通知短信",
        radioNode:"1",
        tem_code:"",
        tem_name:"",
        tem_describe:"",
      },
      infoFormObject:{
        content_json:[],
        NewContent:"",
        MessageName:"",
        store_id:"",
        phoneNumber:"",
      },
      formDialongList:null, //弹框里面的表格数据
      formDialongInline:{ //弹框里面的
        currentPage: 1,
        totalDataNumber: 0,
        listLoading:false,
      },
      formDialong:{  //弹框里面的搜索数据
        begin_time:"",
        end_time: "",
        name:"",
        type:"",
        tem_type:0,
        code:"",
        enable:1
      },
      template_list:[{
        id:0,name:"按模板名称",
      },{
        id:1,name:"按模板CODE",
      }],
      rules: {
        MessageName: [{ required: false, validator: vName, trigger: "blur" }],
        phoneNumber: [{ required: false, validator: vPname, trigger: "blur" }],
        store_id:[{ required: true, validator: vStore, trigger: "change" }]
      },
    }
  },
  activated(){
    const _self=this;
    if(_self.$route.params.data){
      _self.contentDetails(_self.$route.params.data);
    }
  },
  created() {
    this.listArray();
  },
  watch:{
    "infoFormObject.content_json": {
      handler(){
        if(this.isDisabled){return }
        let reg1=/[A-Za-z_]\w*/ig;
        let reg=/[$][{][A-Za-z_]\w*[}]/g;
        let content=this.infoFormList.content;
        let arrReg=this.infoFormList.content.match(reg);
        if(arrReg){
          for(var i=0;i<arrReg.length;i++){
            let key=arrReg[i].match(reg1);
            if(this.infoFormObject.content_json[i][key].indexOf(arrReg[i]) == -1 && this.infoFormObject.content_json[i][key]){
              content  = content.replace(arrReg[i],this.infoFormObject.content_json[i][key]);
            }
          }
          this.infoFormObject.NewContent = content;
        }
      },deep:true
    },
    "formInline.type"(oldValue,newValue){
      switch (this.formInline.type) {
        case '0':
          this.formInline.template_code="";
          this.formInline.template_name="";
          break;
        case '1':
          this.formInline.sample_name="";
          this.formInline.template_code="";
          break;
        case '2':
          this.formInline.sample_name="";
          this.formInline.template_name="";
          break;
      }
    }
  },
  methods:{
    fetchData(){ //搜索
      optionMaxTime369(this.pickerDate).then(()=>{
          this.formInline.begin_time=this.pickerDate[0];
          this.formInline.end_time=this.pickerDate[1];
          this.listArray();
      });
    },
    listArray(){  //获取数据
      this.listLoading = true;
      this.formInline.begin_time=this.pickerDate[0];
      this.formInline.end_time=this.pickerDate[1];
      this.list = [];
      getMessageInfoPage(this.formInline).then(response=>{
        this.totalDataNumber = response.data.count / 1;
        if (this.totalDataNumber == 0) {
          this.listLoading = false;
        } else {
          getMessageInfo(this.formInline).then(res=>{
            this.list = res.data;
            this.listLoading = false;
          });
        }
      });
    },
    addTypeClick() {  //发送短信
      this.addTypeDialog = true;
      //获取模板数据
      this.dialongFetchData();
    },
    dialongFetchData(){  //弹框里的搜索
      this.formDialongList = [];
      this.formDialongInline.listLoading = true;
      if(this.formDialong.tem_type==0){
        this.formDialong.code="";
      }else{
        this.formDialong.name="";
      }
      getLinkInfoPage(this.formDialong).then(response=>{
        this.formDialongInline.totalDataNumber = response.data.count / 1;
        if (this.formDialongInline.totalDataNumber == 0) {
          this.formDialongInline.listLoading = false;
        } else {
          getLinkInfo(this.formDialong).then(res=>{
            this.formDialongList = res.data;
            this.formDialongInline.listLoading = false;
          });
        }
      });
    },
    contentDetails(listArray){  //表格里的详情
      this.tab_view=2;
      this.isDisabled=false;
      this.top_title="短信模板";
      this.addTypeDialog = false;
      this.$refs.infoForm.resetFields();
      this.infoForm.numberList=[];
      this.infoFormObject={
        content_json: [],
        MessageName:"",
        NewContent:listArray.content,
        store_id:"",
        phoneNumber:"",
      };
      this.infoFormList=listArray;
      let reg1=/[A-Za-z_]\w*/ig;
      let reg=/[$][{][A-Za-z_]\w*[}]/g;
      let arrReg=listArray.content.match(reg);
      if(arrReg){
        for(let i=0;i<arrReg.length;i++){
          let key=arrReg[i].match(reg1); //name ,tome,number 变量
          this.infoFormObject.content_json.push({[key]:""});
          Object.assign(this.rules,{
             [key]:[{ required: false, validator: (rule, value, callback) => {
                 if (!this.infoFormObject.content_json[i][key]) {
                   callback(new Error("请填写变量"+(i+1)+"信息"));
                 } else {
                   callback();
                 }
               }, trigger: "blur" }],
          });
        }
      }
    },
    handleCurrentChange(val) {  //获取某个分页的数据
      this.listLoading = true;
      getMessageInfo(this.formInline,val).then(res=>{
        this.list = res.data;
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
      });
    },
    dialongCurrentChange(val){
      this.formDialongInline.listLoading = true;
      getLinkInfo(this.formDialong,val).then(res=>{
        this.formDialongList = res.data;
        this.formDialongInline.listLoading = false;
      }).catch(res => {
        this.formDialongInline.listLoading = false;
      });
    },
    backClick() {  //详情里的返回按钮
      if (!this.isDisabled) {
        this.$confirm(
            "返回后已修改的数据不会保存，是否放弃本次操作？",
            "提示",
            {type: "warning"}
        ).then(() => {
          this.tab_view = 1;
          this.$refs.infoForm.resetFields();
        });
      }else{
        this.tab_view = 1;
        this.$refs.infoForm.resetFields();
      }
    },
    detailsList(arrList){
      this.tab_view=2;
      this.isDisabled=true;
      this.top_title="短信详情";
      this.addTypeDialog = false;
      this.$refs.infoForm.resetFields();
      this.infoForm.numberList=[];
      let content_json=[];

      if(arrList.content_json.length){
        for(let key in JSON.parse(arrList.content_json)){
          content_json.push({[key]:JSON.parse(arrList.content_json)[key]})
        }
      }

      this.infoFormList={
        type:arrList.type,
        code:arrList.code,
        content:arrList.template,
        name:arrList.template_name
      };

      this.infoFormObject={
        content_json: content_json,
        MessageName:arrList.name,
        NewContent:arrList.content,
      };
    },
    editClick(){  //发送短信
      this.$refs.infoForm.validate((valid) => {
        if(valid){
          if(this.infoFormObject.NewContent.length>300){
            this.$confirm('当前短信内容已超出300字，请重新调整后在发送', '提示', {
              confirmButtonText: '确定',
              showCancelButton:false,
              type: 'warning'
            }).then(() => {
              //点击确定的操作(调用接口)
            })
            return
          }
          this.save();
        }
      });
    },
    save(){
      let content_json = {};
      for(var i=0;i<this.infoFormObject.content_json.length;i++){
        Object.assign(content_json,this.infoFormObject.content_json[i]);
      }

      sampleCreate({
        name:this.infoFormObject.MessageName,
        content_json:content_json,
        template_id:this.infoFormList.id
      }).then(res=>{
        if(res.code==1){
          this.$message.success(res.message);
          this.$refs.infoForm.resetFields();
          this.tab_view=1;
          this.listArray();
        }
      })
    },
    goToPage(index,row){
      this.$router.push({
        name:"information/short_record",
        params:{index:index,data:row}
      })
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customContainer {
  overflow-y: auto;
}
.longlinks{
  display:-webkit-box;
  text-overflow:ellipsis;
  overflow:hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient:vertical;
}
.main{
  .main_botton{
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    button{
      width: 100px;
      height: 35px;
      line-height: 10px;
    }
  }
}
.colortext{
  font-size: 14px;
  margin-top: 20px;
  p{
    margin: 0;
  }
}

.info {
  background: #fff;
  padding: 30px 0 10px;
  margin-bottom: 20px;
}

.tab_title {
  width: 200px;
  font-size: 20px;
  font-weight: bold;
  margin: 5px 0 20px 70px;
}


.op_title {
  margin: 30px 0 20px;
  font-size: 16px;
  font-weight: bold;
  color: #282828;
  padding:0 0 10px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #dcdfe6;
}

.num{
  position: relative;
  top: 0;
  left: 0;

  .font{
    position: absolute;
    bottom: 0;
    right: 12px;
  }
}
.red{
  color: red;
}
</style>
